package com.jeequan.jeepay.mgr.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeequan.jeepay.core.entity.PayOrder;
import com.jeequan.jeepay.core.entity.PayOrderFlow;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.mgr.config.ExcelResultHandler;
import com.jeequan.jeepay.service.mapper.PayOrderFlowMapper;
import com.jeequan.jeepay.service.mapper.PayOrderMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FlowOrderService {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private PayOrderFlowMapper payOrderFlowMapper;


    public List<PayOrderFlow> getRentMapList(String createTimeStart, String createTimeEnd, String dealType,String appArray) {

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("dealType", dealType);
        paramMap.put("appArray",appArray);
        paramMap.put("createTimeStart", createTimeStart);
        paramMap.put("createTimeEnd", createTimeEnd);

        //return payOrderFlowMapper.selectMerchantOrder(paramMap);
        return payOrderFlowMapper.selectMerchantAccount(paramMap);
    }

    public void exportFlowOrder(PayOrder payOrder, JSONObject paramJSON) throws IOException, ParseException {

        List<String> headerArray = Arrays.asList("支付订单号", "商户名称", "应用名称", "支付金额", "退款金额", "用户ID", "业务ID", "部门ID", "交易类型", "支付通道", "支付方式", "商品标题", "创建时间", "支付结果");

        List<String> fieldArray = Arrays.asList("payOrderId","mchName", "appName","amount","refundAmount","pid","businessId","deptId", "dealType","wayCode", "paySource","subject", "createdAt", "payResult");

        QueryWrapper<PayOrder> queryWrapper=new QueryWrapper<>();

        if (StringUtils.isNotEmpty(payOrder.getPayOrderId())) {
            queryWrapper.eq("o.pay_order_id", payOrder.getPayOrderId());
        }
        if (StringUtils.isNotEmpty(payOrder.getMchNo())) {
            queryWrapper.eq("o.mch_no", payOrder.getMchNo());
        }
        if (StringUtils.isNotEmpty(payOrder.getIsvNo())) {
            queryWrapper.eq("o.isv_no", payOrder.getIsvNo());
        }
        if (payOrder.getMchType() != null) {
            queryWrapper.eq("o.mch_type", payOrder.getMchType());
        }
        if (StringUtils.isNotEmpty(payOrder.getWayCode())) {
            queryWrapper.eq("o.way_code", payOrder.getWayCode());
        }
        if (StringUtils.isNotEmpty(payOrder.getMchOrderNo())) {
            queryWrapper.eq("o.mch_order_no", payOrder.getMchOrderNo());
        }
        if (payOrder.getState() != null) {
            queryWrapper.eq("o.state", payOrder.getState());
        }
        if (payOrder.getNotifyState() != null) {
            queryWrapper.eq("o.notify_state", payOrder.getNotifyState());
        }
        if (StringUtils.isNotEmpty(payOrder.getAppId())) {
            queryWrapper.eq("o.app_id", payOrder.getAppId());
        }
        if (payOrder.getDivisionState() != null) {
            queryWrapper.eq("o.division_state", payOrder.getDivisionState());
        }

        if (paramJSON != null) {

            final String createdStart = paramJSON.getString("createdStart");
            final String createEnd = paramJSON.getString("createdEnd");

            if (!StringUtils.isEmpty(createdStart)) {
                queryWrapper.ge("o.created_at", createdStart);
            }
            if (!StringUtils.isEmpty(createEnd)) {
                queryWrapper.le("o.created_at", createEnd);
            }

        }
        //根据业务Id查询
        if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getString("businessId"))) {
            queryWrapper.apply("CASE WHEN JSON_VALID(ext_param) THEN JSON_EXTRACT(ext_param,'$.businessId')={0} ELSE null END"
                    , paramJSON.getString("businessId"));
        }
        // 三合一订单
        if (paramJSON != null && StringUtils.isNotEmpty(paramJSON.getString("unionOrderId"))) {
            queryWrapper.and(wr -> {
                wr.eq("o.pay_order_id", paramJSON.getString("unionOrderId"))
                        .or().eq("o.mch_order_no", paramJSON.getString("unionOrderId"))
                        .or().eq("o.channel_order_no", paramJSON.getString("unionOrderId"));
            });
        }

        queryWrapper.orderByDesc("o.created_at");

        Integer dataCount = payOrderFlowMapper.selectOrderFlowCount(queryWrapper);
        if (dataCount > 50000) {
            throw new BizException("查询数据量过大,请缩小查询范围！");
        }

        String exportExcelFileName = "订单流水";
        ExcelResultHandler<PayOrderFlow> handler = new ExcelResultHandler<PayOrderFlow>(headerArray, fieldArray, exportExcelFileName, true) {
            public void tryFetchDataAndWriteToExcel() {
                payOrderFlowMapper.orderStreamQuery(queryWrapper, this);
            }
        };
        handler.ExportExcel();
    }
}